<?

/* * *************************************************************************
  Descri��o: Esta classe retorna o codigo da disciplina a ser insersida.
  Autor: Fernando Maia da Mota
 * ************************************************************************* */

class xGestaoDate {

    public function setAlocacao($codigo, $dataAlocacao, $itenRecurso) {
        $message = Message::singleton();
        try {
            $userId = User::singleton()->getId();
            $db = Database::singleton();

            $sth = $db->prepare("select horarioid  from alocacao.horario where codigo='$codigo'");

            $sth->execute();

            $obj = $sth->fetch(PDO::FETCH_OBJ);

            $_horario = $obj->horarioid;


            //RECUPERA O CODIGO DA ACAO
            $sth = $db->prepare("INSERT INTO alocacao.alocacao(
                         dataalocacao, _itensrecurso, _horario, _user)
                          VALUES ( '$dataAlocacao', $itenRecurso, $_horario, $userId); ");

            $sth->execute();

            $message->addMessage(__('Reservado com Sucesso!'));
            //retorna o codigo do registro
            $return = "ok";
        } catch (PDOException $e) {
            toLog($e->getMessage());

            $message->addWarning($e->getMessage());

            $return = $e->getMessage();
        } catch (Exception $e) {
            toLog($e->getMessage());

            $message->addWarning($e->getMessage());

            $return = $e->getMessage();
        }

        $message->save();

        $this->showMessages();

        return $return;
    }

   
    public function desalocarItem($codigo, $dataAlocacao, $itenRecurso) {
        $message = Message::singleton();
        try {
            $userId = User::singleton()->getId();
            $db = Database::singleton();

            $sth = $db->prepare("select horarioid  from alocacao.horario where codigo='$codigo'");

            $sth->execute();

            $obj = $sth->fetch(PDO::FETCH_OBJ);

            $_horario = $obj->horarioid;


            //RECUPERA O CODIGO DA ACAO
            $sth = $db->prepare("DELETE FROM alocacao.alocacao
                    WHERE _itensrecurso=$itenRecurso and _horario=$_horario and dataalocacao='$dataAlocacao'; ");

            $sth->execute();
            $message->addMessage(__('Reserva Cancelada com Sucesso!'));
            //retorna o codigo do registro
            $return = "ok";
        } catch (PDOException $e) {
            toLog($e->getMessage());

            $message->addWarning($e->getMessage());

            $return = $e->getMessage();
        } catch (Exception $e) {
            toLog($e->getMessage());

            $message->addWarning($e->getMessage());

            $return = $e->getMessage();
        }

        $message->save();

        $this->showMessages();

        return $return;
    }

     public function validaData($dataAlocacao) {
        $message = Message::singleton();
        try {

            $today = date("Y-m-d");
            // primeira data
            // trabalhando a primeira data
            $dataAtual = strtotime($today);

            // trabalhando a segunda data
            $dataEscolhida = strtotime($dataAlocacao);

            $data = date("Y-m-d", time()+ 3600 * 24 * 7);

            // trabalhando a segunda data
            $dataLimite = strtotime($data);

            if ($dataEscolhida >  $dataLimite ) {
                $message->addWarning(__('A data escolhida passa da data limite para Reserva(7 dias)!'));
                $return = false;
            } else {
                if ($dataAtual  > $dataEscolhida) {
                    $return = $data;
                    $message->addWarning(__('A data escolhida &eacute; menor do que a data atual!'));
                    $return = false;
                }else
                    $return = true;
            }
        } catch (Exception $e) {
            toLog($e->getMessage());

            $message->addWarning($e->getMessage());

            $return = $e->getMessage();
        }

        $message->save();

        $this->showMessages();

        return $return;
    }


     public function verificaBloqueio() {

        $userId = User::singleton()->getId();

        $message = Message::singleton();
        try {
             $today = date("Y-m-d");
            // primeira data
          

            $db = Database::singleton();

            $sql="select
	A.alocacaoid , A.dataalocacao, IR.descricao as itenrecurso, R.descricao as recurso
from alocacao.alocacao A
inner join alocacao.itensrecurso IR ON IR.itensrecursoid=A._itensrecurso
inner join alocacao.recurso R ON R.recursoid=IR.itensrecursoid
where A._situacao=1  and A._user=$userId and A.dataalocacao < '$today'
order by A.dataalocacao ";          

            
            $sth = $db->prepare($sql);
            
            $sth->execute();
            
            $count=0;

            // Percorrento um resultset com while
            while ($obj = $sth->fetch(PDO::FETCH_OBJ)) {      
                
                            
                 if($count==0)
                     $dataBloqueio=$obj->dataalocacao;
                 

                 $dataAlocacaoMenosSeteDias_ = strtotime("-7 day", strtotime($obj->dataalocacao));
                 $dataAlocacaoMenosSeteDias = strtotime("-7 day", strtotime($obj->dataalocacao));
                 
                 $dataAlocacao= strtotime($obj->dataalocacao);

                 $dataBloqueioConvertida= strtotime($dataBloqueio);

                if($dataAlocacao <= $dataBloqueioConvertida && $dataBloqueioConvertida >=  $dataAlocacaoMenosSeteDias )
                    $dataBloqueio=date("Y-m-d", strtotime("+7 day", strtotime($dataBloqueio)));
                else
                    $dataBloqueio=$obj->dataalocacao;

                $count++;
            }


            $dataBloqueioConvertida= strtotime($dataBloqueio);

              // trabalhando a primeira data
            $dataAtual = strtotime($today);

            if($dataAtual <= $dataBloqueioConvertida)
                $return= $dataBloqueio;
            else
                 $return= 'livre';                
           

           
        } catch (Exception $e) {
            toLog($e->getMessage());

            $message->addWarning($e->getMessage());

            $return = $e->getMessage();
        }

        $message->save();

        $this->showMessages();

        return  $return;
     
     
    }


    public function loadAgenda($dataInicio, $dataFim, $recurso) {
        try {

            $db = Database::singleton();

            $sth = $db->prepare("select
h.codigo,
u._name,
u._id,
ia.descricao,(
	select case
	 WHEN  count(al.alocacaoid) = 0 THEN '#66ff66' /*#66ff66 verde*/
	  WHEN  count(al.alocacaoid) =(SELECT count(itensrecursoid)
				      FROM alocacao.itensrecurso
				      where _recurso=$recurso) THEN '#f7474f'/*'#f7474f'vermelho*/
	 WHEN  count(al.alocacaoid) < (SELECT count(itensrecursoid)
				      FROM alocacao.itensrecurso
				      where _recurso=$recurso) THEN '#ffff00'/*'#ffff00'amAREL0*/
	end as status
	from alocacao.horario hi
	left join alocacao.alocacao al on hi.horarioid=al._horario and al.dataalocacao  between '$dataInicio' and '$dataFim' 
                    and al._itensrecurso in (select itensrecursoid from alocacao.itensrecurso where _recurso=$recurso)
	where hi.codigo=h.codigo) as status

from alocacao.horario h
left join alocacao.alocacao a on h.horarioid=a._horario and a._itensrecurso in(select itensrecursoid from alocacao.itensrecurso where _recurso=$recurso)
and a.dataalocacao between '$dataInicio' and '$dataFim'
left join alocacao.itensrecurso ia on ia.itensrecursoid=a._itensrecurso
left join public._user u on u._id=a._user");




            $sth->execute();

            $agenda = '';
            // Percorrento um resultset com while
            while ($obj = $sth->fetch(PDO::FETCH_OBJ)) {
                $agenda = $agenda . "$obj->codigo-$obj->status-$obj->_name-$obj->descricao,";
            }
            return $agenda;
        } catch (PDOException $e) {
            toLog($e->getMessage());
            return $e->getMessage();
        } catch (Exception $e) {
            toLog($e->getMessage());
            return $e->getMessage();
        }
    }

    public function loadItensRecurso($recurso, $codigo, $dataAlocacao) {
        try {

            $db = Database::singleton();

            //RECUPERA A DESCRICAO DOS ITENS
            $sth = $db->prepare("SELECT IR.itensrecursoid, IR.descricao
FROM alocacao.itensrecurso IR
where IR.itensrecursoid not in (select itensrecursoid from alocacao.itensrecurso IR
				left JOIN alocacao.alocacao A on A._itensrecurso= IR.itensrecursoid
				left JOIN alocacao.horario H on A._horario= H.horarioid
				where IR._recurso=$recurso and H.codigo='$codigo' and A.dataalocacao='$dataAlocacao')
and IR._recurso=$recurso");

            $sth->execute();

            $count = 0;
            // Percorrento um resultset com while
            while ($obj = $sth->fetch(PDO::FETCH_OBJ)) {
                $itens[$count]['id'] = $obj->itensrecursoid;
                $itens[$count]['descricao'] = $obj->descricao;
                $count++;
            }
            //retorna o codigo do registro               
            if (isset($itens))
                return $itens;
            else
                return 0;
        } catch (PDOException $e) {
            toLog($e->getMessage());
        } catch (Exception $e) {
            toLog($e->getMessage());
        }
    }

    public function loadItensRecursoAlocados($recurso, $codigo, $dataAlocacao) {
        try {
            $userId = User::singleton()->getId();
            $db = Database::singleton();


            //RECUPERA A DESCRICAO DOS ITENS
            $sth = $db->prepare("SELECT IR.itensrecursoid, IR.descricao
FROM alocacao.itensrecurso IR
where IR.itensrecursoid in (select itensrecursoid from alocacao.itensrecurso IR
				left JOIN alocacao.alocacao A on A._itensrecurso= IR.itensrecursoid
				left JOIN alocacao.horario H on A._horario= H.horarioid
				where IR._recurso=$recurso and H.codigo='$codigo' and A._user=$userId and A.dataalocacao='$dataAlocacao')
and IR._recurso=$recurso");

            $sth->execute();

            $count = 0;
            // Percorrento um resultset com while
            while ($obj = $sth->fetch(PDO::FETCH_OBJ)) {
                $itens[$count]['id'] = $obj->itensrecursoid;
                $itens[$count]['descricao'] = $obj->descricao;
                $count++;
            }
            if (isset($itens))
                return $itens;
            else
                return 0;
        } catch (PDOException $e) {
            toLog($e->getMessage());
        } catch (Exception $e) {
            toLog($e->getMessage());
        }
    }

    public function getSemana($dataAlocacao) {
        try {

            $db = Database::singleton();

            $sth = $db->prepare(" SELECT 
                    
cast('$dataAlocacao' AS date) - (
					cast((SELECT extract(DOW FROM TIMESTAMP '$dataAlocacao')) as INTEGER)-0				
					          )
AS domingo,
cast('$dataAlocacao' AS date) - (
					cast((SELECT extract(DOW FROM TIMESTAMP '$dataAlocacao')) as INTEGER)-1					
					          )
AS Segunda,
cast('$dataAlocacao' AS date) - (
					cast((SELECT extract(DOW FROM TIMESTAMP '$dataAlocacao')) as INTEGER)-2					
					          )
AS terca,
cast('$dataAlocacao' AS date) - (
					cast((SELECT extract(DOW FROM TIMESTAMP '$dataAlocacao')) as INTEGER)-3					
					          )
AS quarta,
cast('$dataAlocacao' AS date) - (
					cast((SELECT extract(DOW FROM TIMESTAMP '$dataAlocacao')) as INTEGER)-4					
					          )
AS quinta,
cast('$dataAlocacao' AS date) - (
					cast((SELECT extract(DOW FROM TIMESTAMP '$dataAlocacao')) as INTEGER)-5					
					          )
AS sexta,
cast('$dataAlocacao' AS date) - (
					cast((SELECT extract(DOW FROM TIMESTAMP '$dataAlocacao')) as INTEGER)-6					
					          )
AS sabado
");

            $semana[] = 7;

            $sth->execute();

            $obj = $sth->fetch(PDO::FETCH_OBJ);

            $semana[0] = $obj->domingo;
            $semana[1] = $obj->segunda;
            $semana[2] = $obj->terca;
            $semana[3] = $obj->quarta;
            $semana[4] = $obj->quinta;
            $semana[5] = $obj->sexta;
            $semana[6] = $obj->sabado;


            return $semana;
        } catch (PDOException $e) {
            toLog($e->getMessage());
            return $e->getMessage();
        } catch (Exception $e) {
            toLog($e->getMessage());
            return $e->getMessage();
        }
    }

    public function showMessages() {
        $message = Message::singleton();

        if (!is_object($message) || !$message->has())
            return FALSE;

        $str = '';
        while ($msg = $message->get())
            $str .= $msg;

        $msgs = &XOAD_HTML::getElementById('labelMessage');

        $msgs->innerHTML = '<div id="idMessage">' . utf8_encode($str) . '</div>';

        $message->clear();

        return TRUE;
    }

    public function delay() {
        sleep(1);
    }

    public function xoadGetMeta() {
        $methods = get_class_methods($this);

        XOAD_Client::mapMethods($this, $methods);

        XOAD_Client::publicMethods($this, $methods);

        XOAD_Client::privateMethods($this, array());
    }

}

?>